```html
```
```javascript
document.addEventListener("DOMContentLoaded", function() {
generateCaptcha();
});
function generateCaptcha() {
const captchaLength = 6; // Length of the CAPTCHA code
const captchaChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // Allowed characters for the CAPTCHA code
let captchaCode = "";
for (let i = 0; i < captchaLength; i++) {
captchaCode += captchaChars[randomIndex];
}
const captchaImage = document.getElementById("captchaImage");
captchaImage.src = "generate_captcha_image.php?code=" + captchaCode; // Replace 'generate_captcha_image.php' with your server-side script to generate CAPTCHA images
// Store the generated CAPTCHA code in a hidden input field to verify later
const hiddenInput = document.createElement("input");
hiddenInput.type = "hidden";
hiddenInput.name = "captchaCode";
hiddenInput.value = captchaCode;
const captchaForm = document.getElementById("captchaForm");
captchaForm.appendChild(hiddenInput);
}
// Add form submission validation to check the entered CAPTCHA code
document.getElementById("captchaForm").addEventListener("submit", function(event) {
const captchaInput = document.getElementById("captchaInput").value;
const captchaCode = document.querySelector("input[name='captchaCode']").value;
if (captchaInput !== captchaCode) {
event.preventDefault();
alert("CAPTCHA code is incorrect. Please try again.");
generateCaptcha();
}
});
```
In this example, the JavaScript code generates a random CAPTCHA code of a specified length and displays the code in an image on the form. When the form is submitted, it checks if the entered CAPTCHA code matches the generated one. If not, it prevents the form submission and asks the user to try again. You would need to implement a server-side script (e.g., PHP) to generate the CAPTCHA image and validate the user's input with the generated code. The server-side script would also need to store the correct CAPTCHA code in a session variable or some other mechanism to compare it during form submission.
Please note that this is a very basic example and may not be completely secure on its own. For a more robust CAPTCHA system, consider using industry-standard libraries or services that offer additional features to prevent automated attacks effectively.